<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="100px"
    >
      <el-form-item label="项目负责人" prop="projectManager">
        <el-select
          v-model.trim="formData.projectManager"
          filterable
          placeholder="输入用户昵称进行搜索"
          style="width: 100%"
        >
          <el-option
            v-for="item in projectManager"
            :key="item.id"
            :label="item.nickname"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="测评时间" prop="testTimes">
        <el-date-picker
          v-model="formData.testTimes"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          end-placeholder="结束日期"
          start-placeholder="开始日期"
          type="daterange"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="x"
          style="width: 36%"
        />
      </el-form-item>
      <el-form-item label="交付报告" prop="files">
        <el-upload
          ref="uploadRef"
          v-model:file-list="files"
          :action="importUrl"
          :disabled="formType === 'view'"
          :headers="uploadHeaders"
          :on-success="submitFormSuccess"
          :on-change="handleChange"
          :on-remove="handleRemove"
          :on-error="submitFormError"
          :on-exceed="handleExceed"
          :on-preview="handlePreview"
          :before-upload="beforeUpload"
          drag
          style="width: 100%"
        >
          <Icon icon="ep:upload" />
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <template #tip>
            <div class="el-upload__tip text-center">
              <span>上传单个文件大小不得超过100M</span>
            </div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import * as OrderApi from '@/api/order'
import { getAccessToken, getTenantId } from '@/utils/auth'

defineOptions({ name: 'TestForm' })

const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  orderId: null,
  projectManager: null,
  testTimes: [],
  files: []
})
const formRules = reactive({
  projectManager: [{ required: true, message: '项目负责人不能为空', trigger: 'blur' }],
  testTimes: [{ required: true, message: '测评时间不能为空', trigger: 'blur' }],
  files: [{ required: true, message: '交付报告不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
/** 重置表单 */
const resetForm = () => {
  formData.value = {
    orderId: null,
    projectManager: null,
    testTimes: [],
    files: []
  }
  formRef.value?.resetFields()
  uploadRef.value?.clearFiles()
  files.value = []
}
const projectManager = ref([])
/** 打开弹窗 */
const open = async (row) => {
  dialogVisible.value = true
  dialogTitle.value = '测评交付'
  resetForm()
  projectManager.value = await OrderApi.getProjectManagers({ username: '' })
  // 修改时，设置数据
  if (row.orderId) {
    formLoading.value = true
    try {
      formData.value = {
        orderId: row.orderId,
        projectManager: row.projectManager,
        testTimes: row.testTimes,
        files: row.testReportFile
      }
      if (row.testReportFile) {
        files.value = JSON.parse(row.testReportFile)
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调

/**
 * 选择建议
 * */
// const selectSuggestion = (suggestion) => {
//   formData.value.projectManagerName = suggestion.nickname;
//   formData.value.projectManager = suggestion.id
// }

/**建议过滤*/
// const querySearch = async (queryString: string, cb: any) => {
//   const suggestions = await OrderApi.getProjectManagers({ username: formData.value.projectManagerName })
//   // suggestions.filter((item) => { item.value = item.nickname })
//   // const results = queryString
//   //   ? suggestions.filter(createFilter(queryString))
//   //   : suggestions
//   const results = suggestions
//   cb(results)
// }
// const createFilter = (queryString: string) => {
//   return (restaurant) => {
//     return (
//       restaurant.nickname.indexOf(queryString) === 0
//     )
//   }
// }

const uploadRef = ref()
const files = ref([])
const importUrl =
  import.meta.env.VITE_BASE_URL + import.meta.env.VITE_API_URL + '/testManager/testForm/verify'
const uploadHeaders = ref() // 上传 Header 头
const beforeUpload = (file) => {
  if (file.size / 1024 / 1024 > 100) {
    message.error('上传文件大小不能大于100M')
    return false
  }
}
/** 上传错误提示 */
const submitFormError = (): void => {
  message.error('上传失败，请您重新上传！')
  formLoading.value = false
}
/** 文件数超出提示 */
const handleExceed = (): void => {
  message.error('最多只能上传一个文件！')
}
/** 文件上传成功 */
const submitFormSuccess = (response: any) => {
  if (response.code !== 200) {
    message.error(response.msg)
    formLoading.value = false
    return
  }
}

const handleChange = (uploadFile) => {
  // const isFileSizeValid = uploadFile.size / 1024 < 20;
  // const isPDF = uploadFile.raw.type === 'application/pdf';
  // if (!isPDF) {
  //   message.error('上传文件只能是 PDF 格式!');
  //   files.value = []
  //   return
  // } else {
  formData.value.files = uploadFile
  // }
}

const handleRemove = (a, b) => {
  formData.value.files = b
}

const handlePreview = async (file) => {
  window.open(file.url)
}

const submitDisabled = ref(false)
/** 提交 */
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  uploadHeaders.value = {
    Authorization: 'Bearer ' + getAccessToken(),
    'tenant-id': getTenantId()
  }
  formLoading.value = true
  submitDisabled.value = true
  uploadRef.value!.submit()
  try {
    const data = new FormData()
    const params = {
      ...formData.value
    }
    if (files.value.length) {
      files.value.forEach((item) => {
        if (item.raw) {
          data.append(`files`, item.raw)
        } else {
          data.append(`files`, new Blob([item.url], { type: '' }))
        }
      })
    } else {
      data.append('files', new Blob([], { type: '' }))
    }
    data.append(
      'testDeliverSaveReqVO ',
      new Blob([JSON.stringify(params)], { type: 'application/json' })
    )
    await OrderApi.editTestDeliverInfo(data)
    message.success('测评交付成功')
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
    submitDisabled.value = false
  }
}
</script>

<style scoped lang="scss">
.test-form {
  padding-top: 3%;
}

.test-tree {
  display: flex;
  width: 100%;
}

.test-form-footer {
  display: flex;
  justify-content: center;
}

.custom-tree-node {
  display: flex;
  padding-right: 8px;
  font-size: 14px;
  flex: 1;
  align-items: center;
  justify-content: space-between;
}

.num {
  display: flex;
  // margin: 0 0px 0 0px;
  font-size: 12px;
  color: var(--el-color-primary);
  border-radius: 100%;
  align-items: center;
  justify-content: center;
}

.disabled {
  width: 100%;
  cursor: not-allowed;
}

.tree-node {
  display: flex;
  align-items: center;
}

:deep(.el-tree) {
  padding: 10px 10px 10px 0;

  .el-tree-node {
    .el-tree-node__content {
      // display: flex;
      // justify-content: space-between;
    }

    i.el-tree-node__expand-icon {
      svg {
        display: none;
      }
    }

    i.el-tree-node__expand-icon {
      display: none;
    }
  }

  .el-tree-node.is-current {
    .el-tree-node__content {
      small {
        color: #5e7ce0;
      }
    }

    .el-tree-node__children {
      small {
        color: unset;
      }
    }
  }

  /* ^ 树节点 */
  .el-tree-node {
    position: relative;
    width: auto;
    padding-left: 13px;

    &::before {
      position: absolute;
      inset: -38px auto 0 0;
      width: 1px;
      height: 100%;
      border-left: 1px solid #b8b9bb;
      border-width: 1px;
      content: '';
    }

    &::after {
      position: absolute;
      inset: 12px auto auto 0;
      z-index: 0;
      width: 13px;
      height: 13px;
      border-top: 1px solid #b8b9bb;
      border-width: 1px;
      content: '';
    }

    .el-tree-node__content {
      position: relative;
      z-index: 1;
      padding-left: 0 !important;
    }

    .el-tree-node__children {
      padding-left: 12px;
    }

    &:last-child::before {
      height: 50px;
    }
  }

  > .el-tree-node {
    padding-left: 0;

    &::before {
      border-left: none;
    }

    &::after {
      border-top: none;
    }
  }
}

:deep(.disabled-tree) {
  .el-checkbox {
    pointer-events: none;
    cursor: not-allowed;
  }

  .el-checkbox__input {
    .el-checkbox__inner {
      // 禁用的样式
      background-color: rgb(237 242 252);
      border-color: rgb(217 217 217);
    }

    &.is-checked {
      // 勾选状态下的样式,不加的话禁用时勾选是灰色的
      .el-checkbox__inner {
        background-color: rgb(49 56 69);
        border-color: rgb(49 56 69);
      }
    }
  }
}
</style>
